//
//  HomeCommunityListVC.m
//  jingdongfang
//
//  Created by LJL on 2018/5/24.
//  Copyright © 2018年 BOE. All rights reserved.
//

#import "HomeCommunityListVC.h"
#import "IGEmptyView.h"
#import "HomeCommunityListApi.h"
#import "IGCommunityDetailVC.h"
#import "IGCommunityListTableViewCell.h"
#import "IGCommonApi.h"

@interface HomeCommunityListVC ()<UITableViewDelegate, UITableViewDataSource>
{
    NSString *lastTimeDate;
    NSString *pageSize;
    NSString *pageNum;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) HomeCommunityListApi *listApi;
@property (nonatomic, strong) NSMutableArray *dataSource;
@end

@implementation HomeCommunityListVC

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
//        _tableView.emptyDataSetDelegate = self;
//        _tableView.emptyDataSetSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (instancetype)initWithType:(HomeActivityType)type
{
    if (self = [super init])
    {
        self.type = type;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = (_type == PhotographyType) ? NSLocalizedString(@"home7", nil) : NSLocalizedString(@"home8", nil);
    self.view.backgroundColor = [UIColor mainBackgroundColor];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    __weak typeof(self) weakSelf = self;
    [self.tableView ig_setHeaderWithRefreshingBlock:^{
        pageNum = @"0";
        [weakSelf dataRequest];
    }];
    [self initBaseData];
    
    [self dataRequest];
}

- (void)initBaseData
{
    lastTimeDate = @"";
    pageNum = @"0";
    pageSize = @"10";
    self.listApi = [HomeCommunityListApi new];
    self.dataSource = [@[] mutableCopy];
}

- (void)dataRequest
{
    self.listApi.type = (_type == PhotographyType) ? @"2": @"1";
    self.listApi.lastTimeDate = lastTimeDate;
    self.listApi.pageSize = pageSize;
    self.listApi.pageNum = pageNum;
    __weak typeof(self) weakSelf = self;
    [self.listApi startWithDecodeClass:[HomeCommunityListResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        [weakSelf.tableView ig_endHeaderRefreshing];
        [weakSelf.tableView ig_endFooterRefreshing];
        
        if (responseObject) {
            HomeCommunityListResp *resp = responseObject;
            HomeCommunityListModel *model = resp.data;
            if (model.circles && model.circles.count > 0)
            {
                [weakSelf setupFooter];
            }
            else
            {
                [weakSelf.tableView ig_endFooterRefreshingWithNoMoreData];
            }
            lastTimeDate = model.lastTimeDate;
            if ([pageNum isEqualToString:@"0"])
            {
                _dataSource = [NSMutableArray arrayWithArray:model.circles];
            }
            else
            {
                [_dataSource addObjectsFromArray:model.circles];
            }
            [weakSelf.tableView reloadData];
        } else {
        }
    }];
}

- (void)setupFooter
{
    @KWeakObj(self)
    [self.tableView ig_setFooterWithRefreshingBlock:^{
        pageNum = [NSString stringWithFormat:@"%ld", [pageNum integerValue] + 1];
        [selfWeak dataRequest];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count ? : 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    IGCommunityListTableViewCell *cell = [IGCommunityListTableViewCell cellWithTableView:tableView listType:IGCommunityListTypeMeFollow];
    
    __weak typeof(self) weakSelf = self;
    HomeCommunityModel *model = [self.dataSource objectAtIndex:indexPath.row];
    cell.model = model;
    cell.focusCircle = ^{
        IGCommonApi *commonApi = [[IGCommonApi alloc] initWithApiType:IGiGalleryApiTypeCircleFocusCircle];
        commonApi.circleId = model.cid;
        [commonApi startWithDecodeClass:[IGCommonResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            if (responseObject) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                    [weakSelf presentMessageTips:@"取消成功"];
                    //                    [weakSelf presentMessageTips:NSLocalizedString(@"Canceled Successfully", nil)];
                    model.isFocus = [model.isFocus isEqualToString:@"1"] ? @"0" : @"1";
                    [_dataSource replaceObjectAtIndex:indexPath.row withObject:model];
                    [weakSelf.tableView reloadData];
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                    [weakSelf presentMessageTips:@"取消失败"];
                    //                    [weakSelf presentMessageTips:NSLocalizedString(@"Cancel Failed", nil)];
                });
            }
        }];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HomeCommunityModel *model = [self.dataSource safeObjectAtIndex:indexPath.row];
    if (model) {
        IGCommunityDetailVC *vc = [[IGCommunityDetailVC alloc] initWithCid:model.cid type:GROUP_TITLE_GROUP_DETAILS];
        [UIViewController ig_pushViewController:vc animated:YES];
    }
}


#pragma mark -Empty
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    IGEmptyView *emptyView = [[IGEmptyView alloc] init];
    emptyView.title = NSLocalizedString(@"No Data", nil);
    emptyView.requestApi = self.listApi;
    return emptyView;
}

- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    return YES;
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    return YES;
}

- (void)emptyDataSetDidTapView:(UIScrollView *)scrollView {
    [self dataRequest];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
